﻿using KL.Standard.Model.Infrastructure;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace EagCentralPlatform.Net8.Filter
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private ILogger<GlobalExceptionFilter> _log;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public GlobalExceptionFilter(IWebHostEnvironment env,ILogger<GlobalExceptionFilter> logger)
        {
            _webHostEnvironment = env;
            _log = logger;
        }
        /// <summary>
        /// 异常发生时进入
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                _log.LogError(WriteLog(context.Exception));
                var exceptionMsg = "";
                if (_webHostEnvironment.IsDevelopment())
                     exceptionMsg = context.Exception.Message;
              
                var payload = JsonConvert.SerializeObject(
                    new BaseResult<string> { success = false, errCode = "500", error = $"服务器异常.{exceptionMsg}" });
                //自定义返回的数据类型
                context.HttpContext.Response.ContentType = "application/json";
                //自定义返回状态码，默认为401 我这里改成 200
                context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                //context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                //输出Json数据结果
                context.HttpContext.Response.WriteAsync(payload);
            }
            context.ExceptionHandled = true;
        }

        /// <summary>
        /// 自定义返回格式
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public string WriteLog(Exception ex)
        {
            return string.Format(" \r\n【异常类型】：{0} \r\n【异常信息】：{1} \r\n【堆栈调用】：{2}", new object[] {
                ex.GetType().Name, ex.Message, ex.StackTrace });
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }
    }
}
